<template>
  <div id="manage">
    <div class="condition">
      <div class="secendInput">
        <p>关键字</p>
        <el-input class="input" size="small" v-model="searchParam.keyword" placeholder="请输入角色名或者编号" @keyup.enter.native="refresh()"></el-input>
      </div>
      <el-button class="conditionBtn" size="small" type="primary" @click="refresh()">查询</el-button>
      <el-button class="conditionBtn" size="small" type="primary" @click="isDisabled=false;addOrEditLoad($operType.add)" v-if="power.add">新增</el-button>
    </div>

    <el-table :row-style="{height:'45px'}" :data="tableData" stripe :max-height="tableMaxHeight" class="table">
      <el-table-column v-for="(column, index) in columns" :fixed="column.fixed" :prop="column.prop" :label="column.label" :min-width="column.width" :align="column.align" header-align="center" :key="index" :render="render">
        <template slot-scope="scope">
          <expand v-if="column.render!=null" :render="column.render" :row="scope.row" :index="index" :column="column"></expand>
          <span v-else>{{scope.row[column.prop]}}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="160" align="center" v-if="power.update || power.delete">
        <template slot-scope="scope">
          <el-button type="text" class="primaryTextBtn" @click="isDisabled=false;addOrEditLoad($operType.update,scope.row)" v-if="power.update">修改</el-button>
          <el-button type="text" class="dangerTextBtn" @click="deleteData(scope.row)" v-if="power.delete">删除</el-button>
          <el-button type="text" class="primaryTextBtn" @click="powerDialogVisible = true;rolePower(scope.row)" v-if="power.update"> 权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--新增编辑表单-->
    <el-dialog class="dialogForm" :title="title" v-if="dialogVisible" :visible.sync="dialogVisible" :before-close="handleClose" width="700px" top="10vh" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="line"></div>
      <el-form :ref="ref" :model="formParam" :rules="formParamRules" label-width="120px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="角色名" prop="name">
              <el-input size="small" v-model="formParam.name" name="name" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="角色编号" prop="code">
              <el-input size="small" v-model="formParam.code" name="code" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="角色说明" prop="description">
              <el-input type="textarea" size="small" :rows="2" v-model="formParam.description" name="description" placeholder="请输入角色说明" :disabled="isDisabled">
              </el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" size="small" :rows="2" v-model="formParam.remark" name="remark" placeholder="请输入备注" :disabled="isDisabled">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="formBtn">
        <el-button size="small" type="primary" @click="addOrEditSubmit()" v-if="!isDisabled">确定</el-button>
        <el-button size="small" @click="cancel()" v-if="!isDisabled">取消</el-button>
      </div>
    </el-dialog>

    <!-- 角色权限分配界面 -->
    <el-dialog class="dialogForm" title="角色权限" v-if="powerDialogVisible" :visible.sync="powerDialogVisible" :before-close="handleClose" width="500px" top="10vh" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-container>
        <el-header style="line-height:60px;">
          <el-input size="small" placeholder="输入关键字进行过滤" v-model="powerFilter"> </el-input>
        </el-header>
        <el-main style="height:400px;border: 1px solid #eee;">
          <el-tree :data="powerTree" show-checkbox default-expand-all :filter-node-method="filterNode" node-key="id" :ref="powerTreeRef" highlight-current :props="defaultProps">
          </el-tree>
        </el-main>
        <el-footer class="formBtn" style="line-height:60px;">
          <el-button size="small" type="primary" @click="powerSubmit()">确定</el-button>
          <el-button size="small" @click="cancel()" v-if="!isDisabled">取消</el-button>
        </el-footer>
      </el-container>

    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: "sysRole",
    inject: ["reload"],
    data() {
      var that = this;
      // 获取按钮权限
      let power = {
        query: this.$util.btnShow("sysRole.query"), //查询
        add: this.$util.btnShow("sysRole.add"), //新增
        update: this.$util.btnShow("sysRole.update"), //修改
        delete: this.$util.btnShow("sysRole.delete") //删除
      };

      return {
        clientHeight: document.body.clientHeight, //窗口可视区域高度
        power: power, // 按钮显隐控制权限
        ref: "form",
        powerTreeRef: 'powerTree',
        isDisabled: false, //表单是否可以编辑
        tableMaxHeight: 0, //表格的最大高度
        dialogVisible: false, //表单对话框显隐
        powerDialogVisible: false, //角色权限配置的弹窗
        title: "",
        //搜索条件
        searchParam: {
          type: "0",
          keyword: "",
        },
        // 新增，编辑 表单校验
        formParamRules: {
          name: [{ required: true, message: "请填写角色名", trigger: "blur" }, ],
          code: [{ required: true, message: "请填写角色编号", trigger: "blur" }, ],
        },
        sendType: "", //add 表示新增  edit 表示编辑 view 表示预览
        tableData: [],
        //表格列配置
        columns: [
          { fixed: false, prop: "code", label: "角色编号", width: "200", align: "left" },
          { fixed: false, prop: "name", label: "角色名", width: "200", align: "left" },
          { fixed: false, prop: "description", label: "角色说明", width: '300', align: "left" },
        ],
        // 新增编辑弹出表单
        formParam: {
          id: "",
          code: "", // 编号
          name: "", // 名称
          description: "", // 说明
          type: 1, // 分类：1、角色，2、岗位
          sortNum: "", // 排序码
          remark: "", // 备注
        },

        // 如下为角色分配权限相关
        defaultProps: {
          children: "children",
          label: "label",
          value: "id",
        },
        powerTree: [], //菜单树
        powerFilter: '',
        powerRoleId: '',
        roleType: that.$constant.roleType.role, // 角色分类（角色）
      };
    },
    mounted() {
      var that = this;
      this.refresh();
      this.getPower();
      this.$nextTick(function() {
        //设置表格的最大高度
        setTimeout(function() {
          that.tableMaxHeight = that.$util.setTableMaxHeight(true);
        }, 500);
      });
      window.onresize = () => {
        return (() => {
          window.clientHeight = document.body.clientHeight;
          that.clientHeight = window.clientHeight;
        })();
      };
    },
    watch: {
      clientHeight(val) {
        let that = this;
        setTimeout(function() {
          that.$nextTick(function() {
            heightSet();
            that.tableMaxHeight = that.$util.setTableMaxHeight(true);
          });
        }, 500);
      },
      powerFilter(val) {
        this.$refs[this.powerTreeRef].filter(val);
      }
    },
    methods: {
      handleClose(done) {
        done();
      },
      refresh() {
        //查询
        let that = this;
        var param = new FormData();
        param.append("keyword", this.searchParam.keyword);
        param.append("type", this.searchParam.type);
        that.$req.get(param, api.urlSysRoleList, function(_r) {
          that.tableData = _r.data;
        });
      },
      getPower() {
        //获取菜单
        let that = this;
        that.$req.get({}, api.urlSysMenuTree, function(_r) {
          that.powerTree = _r.data;
        });
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      /**
       * 删除人员
       */
      deleteData(row) {
        let that = this;
        this.$util.msgbox.confrim("是否删除该角色信息?", function() {
          let param = new FormData();
          param.append("id", row.id);
          that.$req.post(param, api.urlSysRoleDelete, function(_r) {
            that.$util.notify.success("删除成功");
            that.refresh();
          });
        });
      },
      /**
       * 添加或者编辑表单加载
       */
      addOrEditLoad(operType, row, th) {
        var that = this;
        this.dialogVisible = true;
        this.title = "角色" + operType.text;
        this.sendType = operType.key;

        if (operType.key == that.$operType.add.key) {
          this.$util.formReset(this.formParam);
          this.formParam.type = this.roleType
        } else {
          var formParam = that.$util.clone_str(row);
          that.formParam = formParam;
        }
      },
      /**
       * 表单提交前的逻辑判断及赋值，根据 sendType 来判断是新增还是编辑  add表示新增edit 表示编辑
       */
      addOrEditSubmit() {
        var that = this;

        var url = '';
        if (this.sendType == this.$operType.add.key) {
          url = api.urlSysRoleAdd;
        } else {
          url = api.urlSysRoleUpdate;
        }

        this.$req.postForm(that.$refs[this.ref], this.formParam, url, function(_r) {
          that.$util.notify.success("操作成功！");
          that.dialogVisible = false;
          that.refresh();
        });
      },
      rolePower(row) {
        let that = this;
        this.powerRoleId = row.id;
        // 获取权限前，先将权限清空
        this.$req.get({ "roleId": this.powerRoleId }, api.urlSysRoleRoleMenus, function(_r) {
          let childData = [];
          if (_r.data) {
            // 设置权限，只设置子节点，父节点无法选择太多
            for (let item of _r.data) {
              let node = that.$refs[that.powerTreeRef].getNode(item)
              if (node && node.isLeaf) {
                childData.push(item)
              }
            }
          }
          that.$refs[that.powerTreeRef].setCheckedKeys(childData);
        });
      },
      powerSubmit() {
        let that = this;
        let param = new FormData();
        param.append('roleId', this.powerRoleId);
        // 获取菜单信息
        let checkKeys = that.$refs[that.powerTreeRef].getCheckedKeys();
        let checkHalfKeys = that.$refs[that.powerTreeRef].getHalfCheckedKeys();
        var menuIds = [...checkKeys, ...checkHalfKeys];
        param.append("menuIds", menuIds);
        this.$req.post(param, api.urlSysRoleSaveRoleMenus, function(_r) {
          that.$util.notify.success("操作成功！");

          that.powerDialogVisible = false;
        });
      },
      /**
       * 取消
       */
      cancel() {
        this.dialogVisible = false;
        this.powerDialogVisible = false;
      },
    },
  };
</script>

<style scoped lang='scss'>
  #manage {
    @include routerView;
  }

  .firstInput {
    @include inputLocation(200px);
  }

  .secendInput {
    @include inputLocation(260px);
  }

  .table {
    @include table;
  }

  .condition {
    @include condition;
  }

  .formBtn {
    @include formBtn;
  }

  .line {
    @include line;
  }

  .conditionBtn {
    @include conditionBtn;
    margin-top: 0px !important;
  }
</style>
<style lang='scss'>
  .dialogForm {
    @include dialogForm;
  }
</style>